package com.petdog.module.tools.controller;

import com.petdog.module.tools.dto.LostPetDTO;
import com.petdog.module.tools.dto.LostPetRequest;
import com.petdog.module.tools.dto.NearbyLostPetsRequest;
import com.petdog.module.tools.dto.UploadSightingRequest;
import com.petdog.module.tools.service.LostPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 寻宠功能控制器
 */
@RestController
@RequestMapping("/api/tools")
@Validated
public class LostPetController {

    @Autowired
    private LostPetService lostPetService;

    /**
     * 发布寻宠启事
     */
    @PostMapping("/lost-pet")
    public ResponseEntity<Map<String, Object>> publishLostPet(
            @Valid LostPetRequest request,
            @RequestParam("petPhoto") MultipartFile petPhoto,
            @RequestAttribute("userId") Long userId) {

        try {
            // 调用服务发布寻宠启事
            Long lostPetId = lostPetService.publishLostPet(request, petPhoto, userId);

            // 构建成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("code", 200);
            result.put("data", Map.of("lostPetId", lostPetId));
            result.put("message", "寻宠启事发布成功，已向附近用户推送");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 构建错误响应
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("code", 500);
            error.put("error", e.getMessage());
            error.put("message", "操作失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 获取附近寻宠启事
     */
    @GetMapping("/nearby-lost-pets")
    public ResponseEntity<Map<String, Object>> getNearbyLostPets(
            @Valid NearbyLostPetsRequest request) {

        try {
            // 调用服务获取附近寻宠启事
            List<LostPetDTO> nearbyLostPets = lostPetService.getNearbyLostPets(request);

            // 构建成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("code", 200);
            result.put("data", Map.of(
                    "lostPets", nearbyLostPets,
                    "total", nearbyLostPets.size(),
                    "page", request.getPage(),
                    "pageSize", request.getPageSize()
            ));
            result.put("message", "操作成功");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 构建错误响应
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("code", 500);
            error.put("error", e.getMessage());
            error.put("message", "操作失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 上传所见宠物
     */
    @PostMapping("/upload-sighting")
    public ResponseEntity<Map<String, Object>> uploadSighting(
            @Valid UploadSightingRequest request,
            @RequestParam("petPhoto") MultipartFile petPhoto,
            @RequestAttribute("userId") Long userId) {

        try {
            // 调用服务上传所见宠物并进行匹配
            Map<String, Object> matchResult = lostPetService.uploadSighting(
                    petPhoto, request.getLongitude(), request.getLatitude(), userId);

            // 构建成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("code", 200);
            result.put("data", matchResult);
            result.put("message", (String) matchResult.get("message"));

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 构建错误响应
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("code", 500);
            error.put("error", e.getMessage());
            error.put("message", "操作失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 标记寻宠启事为已找回
     */
    @PutMapping("/lost-pet/{id}/found")
    public ResponseEntity<Map<String, Object>> markAsFound(
            @PathVariable("id") Long lostPetId,
            @RequestAttribute("userId") Long userId) {

        try {
            // 调用服务标记为已找回
            lostPetService.markAsFound(lostPetId, userId);

            // 构建成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("code", 200);
            result.put("message", "标记成功");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 构建错误响应
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("code", 500);
            error.put("error", e.getMessage());
            error.put("message", "操作失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 获取用户发布的寻宠启事
     */
    @GetMapping("/user/lost-pets")
    public ResponseEntity<Map<String, Object>> getUserLostPets(
            @RequestAttribute("userId") Long userId) {

        try {
            // 调用服务获取用户发布的寻宠启事
            List<LostPetDTO> userLostPets = lostPetService.getUserLostPets(userId);

            // 构建成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("code", 200);
            result.put("data", userLostPets);
            result.put("message", "操作成功");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 构建错误响应
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("code", 500);
            error.put("error", e.getMessage());
            error.put("message", "操作失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    /**
     * 统一异常处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        Map<String, Object> error = new HashMap<>();
        error.put("success", false);
        error.put("code", 500);
        error.put("error", e.getMessage());
        error.put("message", "系统繁忙，请稍后再试");

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}